<template>
	<view class="login" @touchstart.stop @touchmove.stop @touchend.stop>
		<image class="bg-image" src="~@/static/loginBg.png" mode="aspectFill"></image>
		<main class="main">
			<h2>Boke家纺</h2>
			<view class="form-container">
				<u-form labelPosition="left" :model="model1" :rules="rules" ref="uForm" :label-width="120">

					<u-form-item prop="userInfo.name" label="用户名" borderBottom>
						<u-input v-model="model1.userInfo.name" border="none" placeholder="请输入用户名或手机号码"
							@keyup.enter.native="login"></u-input>
					</u-form-item>

					<u-form-item prop="userInfo.password" label="密码" borderBottom>
						<u-input v-model="model1.userInfo.password" border="none" placeholder="请输入密码" type="password"
							@keyup.enter.native="login"></u-input>
					</u-form-item>

					<!-- 登录按钮 -->
					<view class="login-btn-container">
						<u-button class="login-btn" @click="login" :loading="loading" :disabled="loading">
							登录
						</u-button>
					</view>

					<!-- 记住密码和忘记密码选项 -->
					<view class="form-options">
						<view class="remember-me">
							<u-checkbox-group v-model="rememberMeChecked">
								<u-checkbox :name="rememberMeText" shape="circle" active-color="#D533BA"
									:label="rememberMeText">
									<text class="checkbox-text">{{ rememberMeText }}</text>
								</u-checkbox>
							</u-checkbox-group>
						</view>
						<view class="forgot-password" @click="forgotPassword">
							忘记密码?
						</view>
					</view>
				</u-form>

				<!-- 错误信息显示 -->
				<view class="error-message" v-if="errorMessage">
					<text class="error-text">{{ errorMessage }}</text>
				</view>
			</view>
		</main>
	</view>
</template>

<script>
	import JSEncrypt from 'jsencrypt';
	import request from '@/utils/request';
	export default {
		data() {
			return {
				//公钥
				publicKey: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQGVu9dhNTWz+kw5vJifAPnBoppjo7MbqQRlbb93JZzu1lKNs/qzatPE+WFZXOSLFBwsx3CX+UUS8GVQ7yQIDaPImAvQvuRk6/a+cIzh7gDhNrfF90IAaepAbwq4c9n9Z+bkSb/KPbZ6WPmMunhPyuEJxACa6RFEenAt4mojFOBwIDAQAB',
				//私钥
				privateKey: 'MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANAZW712E1NbP6TDm8mJ8A+cGimmOjsxupBGVtv3clnO7WUo2z+rNq08T5YVlc5IsUHCzHcJf5RRLwZVDvJAgNo8iYC9C+5GTr9r5wjOHuAOE2t8X3QgBp6kBvCrhz2f1n5uRJv8o9tnpY+Yy6eE/K4QnEAJrpEUR6cC3iaiMU4HAgMBAAECgYAD4fuknofGlGGs0O5R/yR4uUobraHq6aCetIR5kjWSy2bOh/0FqrIlRVM1OUd6rXLxOsTWq7/mCowjROieFVBruV2Lxk2+PV5lQtKdwpv7xE+T3Oc42Kcm/UcrZjOI6R4sOEceMwq5G1kAQPNgxZM8BJTK5jo3B4VQDML70lvU8QJBAPdtSTnKwMPsyUU9soCHr4BHlsRL78MJtn9k6R4srI9KGwzgBVDR2198QZCm/ucCiJnXkZNEaHKUJ7eOOFejccMCQQDXTzp5pDb9mhq+F9assRItdmCiqY1EHeRzvG8bBH+CdlXNuf1OQS29hkImiPTKW/VvOrMFtzCPCezlrxt7csptAkAkiMmQNAUEqRkLFVIfMmnSqj9z2rabePqukurtHrGYMtwNqaJ/TY1z6vgPcOkgmTosZS1Erowxpvi6XNCq+CJbAkEAxGfimKoC+84CzRsj2j5grZYJyvhOBDAcgLMIyyWMR285EES0XBk652M8nrhaTOob9o4eVn1oT2MnddIJiNAK9QJAHLg9OXkX/UMAP1Q0EFfvCGidrjkAK5kqTTlkRGdZdf/nOVMZlzEhGsBn1cK+nDUvPOC5oKkUWglTcYceamUFPw==',
				model1: {
					userInfo: {
						name: '',
						password: '',
					},
				},
				checkboxGroup: [],
				rememberMeText: '记住密码',
				rememberMeChecked: [], // 添加这个属性定义
				loading: false,
				rules: {
					'userInfo.name': {
						type: 'string',
						required: true,
						message: '请填写用户名',
						trigger: ['blur', 'change']
					},
					'userInfo.password': {
						type: 'string',
						required: true,
						message: '请填写密码',
						trigger: ['blur', 'change']
					}
				},
				errorMessage: ''
			};
		},
		methods: {
			//加密方法
			RSAgetPass(pas) {
				const rsa = new JSEncrypt();
				rsa.setPublicKey(this.publicKey);
				console.log('加密：' + rsa.encrypt(pas))
				return rsa.encrypt(pas)
			},
			login() {
				// 检查uForm引用
				// if (!this.$refs.uForm) {
				// 	this.errorMessage = '表单组件加载失败，请重试';
				// 	return;
				// }

				// 尝试两种验证方式
				try {
					const validateResult = this.$refs.uForm.validate();

					if (validateResult instanceof Promise) {
						// 使用Promise方式验证
						validateResult
							.then(() => {
								this.handleValidForm();
							})
							.catch(errors => {
								this.handleValidationError(errors);
							});
					} else {
						// 使用回调方式验证
						this.$refs.uForm.validate((valid, invalidFields) => {
							if (valid) {
								this.handleValidForm();
							} else {
								this.handleValidationError(invalidFields);
							}
						});
					}
				} catch (error) {
					this.errorMessage = '验证过程中发生错误: ' + error.message;
				}
			},

			async handleValidForm() {
				// this.loading = true;
				const pms = {
					userName: this.model1.userInfo.name,
					pwd: this.RSAgetPass(this.model1.userInfo.password)
				}
				uni.removeStorageSync('token');
				const result = await request.post('/api/okx-bot/v1/user/login', pms, {
					header: {
						'Content-Type': 'multipart/form-data'
					},
				});
				uni.setStorageSync('token', result.token);
				uni.showToast({
					title: '登录成功',
					icon: 'success',
					duration: 2000
				});
				// 延迟500ms跳转，确保Toast显示
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/index/index'
					});
				}, 500);

			},

			handleValidationError(invalidFields) {
				this.errorMessage = '';

				if (invalidFields && Object.keys(invalidFields).length > 0) {
					const firstError = Object.values(invalidFields)[0];
					if (firstError && firstError.message) {
						this.errorMessage = firstError.message;

						// 滚动到错误字段
						if (this.$refs.uForm.scrollToField) {
							this.$refs.uForm.scrollToField(Object.keys(invalidFields)[0]);
						}

						// 3秒后自动清除错误信息
						setTimeout(() => {
							this.errorMessage = '';
						}, 3000);
					}
				} else {
					this.errorMessage = '表单验证失败，请检查输入';
				}
			},

			forgotPassword() {
				uni.showModal({
					title: '忘记密码',
					content: '请联系客服重置密码',
					showCancel: false
				});
			},

			onRememberMeChange(val) {
				const isChecked = val.includes(this.rememberMeText);

				if (isChecked) {
					uni.setStorageSync('savedUserInfo', this.model1.userInfo);
				} else {
					uni.removeStorageSync('savedUserInfo');
				}
			}
		},
		onReady() {
			// 确保表单规则已设置
			if (this.$refs.uForm) {
				this.$refs.uForm.setRules(this.rules);
			}

			// 检查本地存储中是否有记住的密码
			const savedUserInfo = uni.getStorageSync('savedUserInfo');
			if (savedUserInfo) {
				this.model1.userInfo = savedUserInfo;
				this.rememberMeChecked = [this.rememberMeText]; // 初始化选中状态
			}
		},
		watch: {
			'model1.userInfo': {
				handler(newVal) {
					if (this.rememberMeChecked.includes(this.rememberMeText)) {
						uni.setStorageSync('savedUserInfo', newVal);
					}
				},
				deep: true
			}
		}
	}
</script>



<style lang="scss">
	page,
	body {
		height: 100%;
		overflow: hidden;
	}

	.login {
		position: relative;
		width: 100vw;
		height: 100vh;
	}

	.bg-image {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 0;
	}

	.main {
		width: 600rpx;
		height: 800rpx;
		background: rgba(255, 255, 255, 0.8);
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		border-radius: 40rpx;
		z-index: 1;
		box-shadow: 0 10rpx 50rpx rgba(0, 0, 0, 0.1);

		h2 {
			margin: auto;
			text-align: center;
			margin-top: 60rpx;
			font-size: 48rpx;
			background: linear-gradient(to right, #fbe45e, rgb(213, 51, 186));
			-webkit-background-clip: text;
			background-clip: text;
			-webkit-text-fill-color: transparent;
			color: transparent;
			font-weight: bold;
		}
	}

	.formRlues {
		width: 80%;
		background-color: rgba(255, 255, 255, 0.9);
		margin: auto;
		margin-top: 80rpx;
		height: 500rpx;
		padding: 40rpx 30rpx;
		border-radius: 20rpx;
		box-shadow: 0 5rpx 30rpx rgba(0, 0, 0, 0.05);
	}

	/* 登录按钮样式 */
	.login-btn-container {
		margin-top: 60rpx;
		padding: 0 20rpx;
	}

	.login-btn {
		height: 88rpx;
		line-height: 88rpx;
		border-radius: 44rpx;
		font-size: 34rpx;
		font-weight: 500;
		letter-spacing: 2rpx;
		background: linear-gradient(90deg, #fbe45e 0%, #D533BA 100%);
		border: none;
		box-shadow: 0 8rpx 20rpx rgba(213, 51, 186, 0.25);
		transition: all 0.2s;

		&:hover {
			opacity: 0.9;
			transform: translateY(-2rpx);
			box-shadow: 0 10rpx 25rpx rgba(213, 51, 186, 0.3);
		}

		&:active {
			opacity: 0.8;
			transform: translateY(1rpx);
			box-shadow: 0 4rpx 15rpx rgba(213, 51, 186, 0.2);
		}
	}

	/* 表单选项样式 */
	.form-options {
		display: flex;
		justify-content: space-between;
		margin-top: 30rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		color: #666;

		.remember-me {
			.u-checkbox-group {
				display: flex;
				align-items: center;
			}

			.u-checkbox {
				display: flex;
				align-items: center;
			}

			.u-checkbox__text {
				font-size: 28rpx !important;
				margin-left: 8rpx !important;
				color: #666 !important;
			}
		}

		.forgot-password {
			color: #D533BA;
			cursor: pointer;
			font-size: 28rpx;

			&:hover {
				text-decoration: underline;
			}
		}
	}

	.form-container {
		margin: 50rpx 50rpx;
	}
</style>